<!-- eslint-disable indent -->
<template>
  <div class="dashboard-container">
    <l-map
      :zoom="zoom"
      :center="center"
      :options="options"
      @update:center="centerUpdate"
      @update:zoom="zoomUpdate"
    >
      <l-tile-layer v-for="(item,index) in urls" :key="index" :url="item" />
      <l-control>
        <map-tools
          @control="control"
          @showProject="showProject"
          @showPlan="showPlan"
          @showPgPlan="showPgPlan"
          @showWeather="showWeather"
          @showCell="showCell"
          @showMarkers="showMarkers"
          @showPolygons="showPolygons"
          @showPartition="showPartition"
        />
      </l-control>
      <map-markers v-if="markersDialogVisible" @showDevice="showDevice" />
      <map-polygons v-if="polygonsDialogVisible" @showPolygon="showPolygon" />
      <div v-for="(item, index) in cellsFormat" :key="index">
        <map-semi-circle
          v-for="(citem, cindex) in item"
          :key="'semicircle-' + cindex"
          :lat-lng="citem.location"
          :options="citem.options"
          @click="showCircle(citem)"
        />
      </div>
      <l-polyline
        v-for="(item,index) in latlngs"
        :key="`polyline${index}`"
        :lat-lngs="item"
      />
      <l-circle
        v-for="(circle,index) in circles"
        :key="`circle${index}`"
        :lat-lng="circle.center"
        :radius="circle.radius"
        :color="circle.color"
        :fill-color="circle.color"
        :opacity="0"
        @click="showCircle(circle)"
      />
    </l-map>
    <el-dialog
      v-el-drag-dialog
      :title="dclassContainerTitle"
      :visible.sync="dclassContainerVisible"
      width="1000px"
    >
      <dclass-container
        @showDevice="showDevice"
      />
    </el-dialog>
    <el-drawer
      :title="project.name"
      :visible.sync="drawerVisible"
      direction="rtl"
    >
      <project-container :project="project" />
    </el-drawer>
    <el-drawer
      title="灌溉计划"
      :visible.sync="planDrawerVisible"
      direction="rtl"
      :size="480"
    >
      <plan :plan-drawer-visible="planDrawerVisible" />
    </el-drawer>
    <el-drawer
      title="喷灌计划"
      :visible.sync="pgPlanDrawerVisible"
      direction="rtl"
      :size="480"
    >
      <pgPlan :plan-drawer-visible="pgPlanDrawerVisible" />
    </el-drawer>
    <el-dialog
      :title="deviceContainerTitle"
      :visible.sync="deviceContainerVisible"
      width="1380px"
      @close="dialogClose"
    >
      <span
        v-if="currentDevice"
        slot="title"
        class="device-header"
      >
        <el-image
          class="device-image"
          :src="getDeviceImage(currentDevice)"
          :style="getDeviceStyle(currentDevice)"
          :fit="fit"
        />
        {{ currentDevice.name + ' —— ' + currentDevice.serialno }}
        <template v-if="[+dclassCodeMap.cqz,+dclassCodeMap.bzy].includes(+currentDevice.product_type)">
          <el-button type="primary" icon="el-icon-picture" class="ml12" size="mini" @click="openImages">查看图片</el-button>
          <el-button type="success" icon="el-icon-s-data" size="mini" @click="openCensus">查看统计信息</el-button>
        </template>
      </span>
      <scd />
      <bzy />
      <cqz />
      <dg />
      <sf />
      <sb />
      <pg />
      <qxz />
      <sqz />
      <gcwd />
      <gd />
      <ndvi />
      <gps />
      <spjk />
      <zyp />
      <fdj />
      <llj />
      <fkq />
      <gdgcwd />
      <df />
      <zk />
      <wg />
      <qf />
      <hjjc />
      <pressure />
      <spj />
    </el-dialog>
    <el-dialog
      v-el-drag-dialog
      :title="cellDialogTitle"
      :visible.sync="cellDialogVisible"
      :modal="false"
      width="1100px"
    >
      <cell />
    </el-dialog>
    <el-dialog
      title="分区管理"
      append-to-body
      :visible.sync="partitionShow"
      fullscreen
      @close="partitionDialogClose"
    >
      <partition :partition-serialno="partitionSerialno" @switchProject="switchProject" />
    </el-dialog>
    <weather-container
      v-show="weatherVisible"
      :weather-data="weatherData"
      @showWeather="showWeather"
    />
    <mqtt-container
      ref="mqttContainer"
    />
    <Legend class="legend" />
  </div>
</template>

<script>
import MqttContainer from '@/components/MqttContainer'
import MapTools from './components/map-tools'
import DclassContainer from './components/dclass-container'
import ProjectContainer from './components/project-container'
import WeatherContainer from './components/weather-container'
import Legend from './components/legend'
import Plan from '@/views/plan/index'
import PgPlan from '@/views/pgPlan/index'
import MapMarkers from './components/map-markers'
import MapPolygons from './components/map-polygons'
import Scd from '@/components/Device/Scd'
import Bzy from '@/components/Device/Bzy'
import Cqz from '@/components/Device/Cqz'
import Dg from '@/components/Device/Dg'
import Sf from '@/components/Device/Sf'
import Sb from '@/components/Device/Sb'
import Pg from '@/components/Device/Pg'
import Qxz from '@/components/Device/Qxz'
import Sqz from '@/components/Device/Sqz'
import Gcwd from '@/components/Device/Gcwd'
import Gd from '@/components/Device/Gd'
import Ndvi from '@/components/Device/Ndvi'
import Gps from '@/components/Device/Gps'
import Spjk from '@/components/Device/Spjk'
import Zyp from '@/components/Device/Zyp'
import Zk from '@/components/Device/Zk'
import Wg from '@/components/Device/Wg'
import Fdj from '@/components/Device/Fdj'
import Llj from '@/components/Device/Llj'
import Fkq from '@/components/Device/Fkq'
import Gdgcwd from '@/components/Device/Gdgcwd'
import Df from '@/components/Device/Df'
import Qf from '@/components/Device/Qf'
import Hjjc from '@/components/Device/Hjjc'
import Pressure from '@/components/Device/Pressure'
import Spj from '@/components/Device/Spj'
import Blg from '@/components/Device/Blg'
import Cell from '@/views/cell'
import Partition from './components/partition'
import elDragDialog from '@/directive/el-drag-dialog'
import map from '@/config/map'
import { dclassMap, dclassCodeMap } from '@/utils/constant'
import { getDeviceStatus, getDeviceImage } from '@/utils/device'
import { parseTime, getDateDiff, deepClone, arraySort } from '@/utils'
import { getWeather } from '@/api/project'
import { mapGetters } from 'vuex'
import MapSemiCircle from './components/map-semi-circle'
import * as turf from '@turf/turf'
export default {
  name: 'Dashboard',
  components: {
    MqttContainer,
    MapSemiCircle,
    MapTools,
    DclassContainer,
    ProjectContainer,
    WeatherContainer,
    Plan,
    PgPlan,
    Partition,
    MapMarkers,
    MapPolygons,
    Scd,
    Bzy,
    Cqz,
    Dg,
    Sf,
    Sb,
    Pg,
    Qxz,
    Sqz,
    Gcwd,
    Gd,
    Ndvi,
    Gps,
    Spjk,
    Zyp,
    Fdj,
    Llj,
    Fkq,
    Gdgcwd,
    Df,
    Qf,
    Zk,
    Wg,
    Hjjc,
    Pressure,
    Spj,
    Cell,
    Legend
  },
  directives: { elDragDialog },
  inject: ['reload'],
  data() {
    return {
      messages: 0,
      zoom: map.zoom,
      center: map.center,
      options: map.options,
      urls: map.mapTypes['map.initType'],
      typeIndex: 0,
      dclassContainerTitle: '设备控制',
      dclassContainerVisible: false,
      drawerVisible: false,
      weatherVisible: true,
      weatherData: null,
      deviceContainerTitle: '',
      deviceContainerVisible: false,
      dclassMap,
      dclassCodeMap,
      currentDevice: null,
      fit: 'fill',
      planDrawerVisible: false,
      pgPlanDrawerVisible: false,
      cellDialogTitle: '轮灌组编排',
      cellDialogVisible: false,
      markersDialogVisible: false,
      polygonsDialogVisible: false,
      partitionShow: false,
      partitionSerialno: ''
    }
  },
  computed: {
    ...mapGetters(['project', 'devicesObj', 'tuliShow', 'devices', 'cells']),
    cellsFormat() {
      const cells = deepClone(this.cells)
      for (const item in cells) {
        cells[item] = arraySort(cells[item], 'disend')
      }
      return cells
    },
    latlngs() {
      const sprinklers = this.devices.filter((val) => {
        return +val.product_type === +dclassCodeMap.pg && val.settings && val.settings.radius !== undefined
      }) || []
      const res = []
      sprinklers.forEach((item) => {
        const startPos = [+item.lng, +item.lat]
        const radius = (+item.settings.radius) / 1000
        let angle = 0
        if (item.states.Angle !== undefined) {
          angle = +item.states.Angle
        }
        if (item.states.REG_HMI_GPS !== undefined) {
          angle = +item.states.REG_HMI_GPS
        }
        const endPos = this.getPoint(startPos, radius, angle)

        res.push([[startPos[1], startPos[0]], [endPos[1], endPos[0]]])
      })
      console.log(res)
      return res
    },
    circles() {
      const sprinklers = this.devices.filter((val) => {
        return +val.product_type === +dclassCodeMap.pg && val.settings && val.settings.radius !== undefined
      }) || []
      const res = []
      sprinklers.forEach((item) => {
        if (item.cells.length === 0) {
          res.push({
            serialno: item.serialno,
            radius: item.settings.radius,
            center: [+item.lat, +item.lng],
            color: 'rgba(248, 9, 9, 1)'
          })
        }
      })
      return res
    }
  },
  watch: {
    weatherVisible: {
      handler(newVal) {
        if (newVal) {
          this.getWeather()
        }
      },
      immediate: true
    },
    project: {
      handler(newVal) {
        this.markersDialogVisible = newVal.show_device || false
        this.polygonsDialogVisible = newVal.show_field || false
        if (newVal.map) {
          this.urls = map.mapTypes[newVal.map]
        }
      },
      immediate: true,
      deep: true
    },
    devices: {
      handler(newVal) {
        if (this.project.show_message && this.messages < 6) {
          const troubles = newVal.filter((val) => {
            const now = parseTime(new Date().getTime())
            const datatime = val.states && val.states.datatime
            if (datatime) {
              return getDateDiff(datatime, now, 'hour') > this.project.timetran
            }
          })
          const message = '编号为 <b style="color:#F56C6C;">' + troubles.map((val) => val.serialno).join('，') + '</b> 的设备' + (this.project.message || '')
          this.$notify({
            title: '提示',
            message: message,
            type: 'error',
            duration: 60000,
            dangerouslyUseHTMLString: true,
            customClass: 'intelirri-notification'
          })
          this.messages++
        }
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    this.center = [this.project.lat, this.project.lng]
    this.zoom = this.project.maplevel
    this.setWeatherVisible()
  },
  beforeRouteLeave(to, from, next) {
    try {
      this.$refs.mqttContainer.destroyConnection()
      next()
    } catch (error) {
      next()
    }
  },
  methods: {
    getDeviceStyle(device) {
      if (+device.product_type === +dclassCodeMap.qf) {
        const A = (device.states && device.states.A) || 90
        const degree = Math.round(A / 100)
        return {
          transform: `rotate(${degree - 90}deg)`,
          transition: 'transform 0.5s ease' // 可选的过渡效果
        }
      }
    },
    partitionDialogClose() {
      this.partitionSerialno = ''
    },
    getPoint(startPos, distance, bearing) {
      const point = turf.point(startPos)
      const destination = turf.destination(point, distance, bearing)

      return destination.geometry.coordinates
    },
    zoomUpdate(zoom) {
      this.zoom = zoom
    },
    centerUpdate(center) {
      this.center = center
    },
    control() {
      this.dclassContainerVisible = true
    },
    showProject() {
      this.drawerVisible = true
    },
    showWeather() {
      this.weatherVisible = !this.weatherVisible
    },
    showDevice(currentDevice) {
      this.currentDevice = currentDevice
      this.$store.commit('device/SET_CURRENT_DEVICE', currentDevice)
      this.$store.commit('device/SET_CURRENT_DEVICE_SHOW', true)
      this.serialno = currentDevice.serialno
      this.deviceContainerTitle = currentDevice.name
      this.deviceContainerVisible = true
    },
    showPlan() {
      this.planDrawerVisible = true
    },
    showPgPlan() {
      this.pgPlanDrawerVisible = true
    },
    showCell() {
      this.cellDialogVisible = true
    },
    showMarkers() {
      this.markersDialogVisible = !this.markersDialogVisible
    },
    showPolygons() {
      this.polygonsDialogVisible = !this.polygonsDialogVisible
    },
    getDeviceStatus(device) {
      return getDeviceStatus(device)
    },
    getDeviceImage(device) {
      return getDeviceImage(device)
    },
    dialogClose() {
      this.$store.commit('device/SET_CURRENT_DEVICE_SHOW', false)
    },
    switchProject() {
      this.reload()
    },
    async getWeather() {
      getWeather(this.project.id).then(res => {
        this.weatherData = res.data
      })
        .catch(() => {
          this.$notify.error('获取天气信息失败')
        })
    },
    showCircle(item) {
      this.showDevice(this.devicesObj[item.serialno])
    },
    showPolygon(item) {
      if (item.dg_serialno) {
        this.showDevice(this.devicesObj[item.dg_serialno])
      }
      if (item.policyable) {
        this.$router.push({ name: 'statistics-index' })
      }
    },
    showPartition() {
      this.partitionShow = true
    },
    setWeatherVisible() {
      const d = new Date()
      const weatherKey = [d.getFullYear(), d.getMonth(), d.getDay()].join('-') + 'weather'
      if (localStorage.getItem(weatherKey)) {
        this.weatherVisible = false
      } else {
        localStorage.setItem(weatherKey, 1)
      }
    },
    openImages() {
      const url = this.createLink(this.currentDevice.gw_serialno, 'image')
      this.openFullWindow(url)
    },
    openCensus() {
      const url = this.createLink(this.currentDevice.gw_serialno, 'stat')
      this.openFullWindow(url)
    },
    createLink(serialno, type) {
      const { username, password } = this.getUsernameAndPassword(serialno)
      return `http://mengchuangyun.cn/public/insect/${type}/${serialno}?username=${username}&password=${password}`
    },
    getUsernameAndPassword(serialno) {
      if (['AA73F68E6261817E', 'E1BF32A219403BDC', '14A82F67FC01BB15', '868618054176862', '868618054177043', '868618054195144'].includes(serialno)) {
        return {
          username: 'xank20241l@myun.com',
          password: '123456'
        }
      }
      return {
        username: 'mltl@myun.com',
        password: '123456'
      }
    },
    openFullWindow(url, winname = '_blank') {
      let strFeatures = 'left=30,screenX=30,top=30,screenY=30'
      if (window.screen) {
        const screen = window.screen
        // 获取屏幕的分辨率
        var maxh = screen.availHeight - 60
        var maxw = screen.availWidth - 60
        strFeatures += ',height=' + maxh
        strFeatures += ',innerHeight=' + maxh
        strFeatures += ',width=' + maxw
        strFeatures += ',innerwidth=' + maxw
      } else {
        strFeatures += ',resizable '
      }
      window.open(url, winname, strFeatures)
    }
  }
}
</script>

<style lang="scss" scoped>
a.link{
  margin-left:16px;
  font-size:14px;
  color:#666;
}
.dashboard {
  &-container {
    width:100%;
    height:calc(100vh - 50px);
  }
  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}
.device-image{
  width:32px;
  height:32px;
  margin-right:8px;
}
</style>

<style lang="scss">
.device-header{
  font-size:16px;
  display:flex;
  align-items:center;
}
dashboard-container{
  position:relative;
}
.legend,
  .blockShow {
    position: absolute;
    z-index: 999;
    bottom: 10px;
    right: 10px;
    font-size:14px;
  }
</style>
